﻿using FluentNHibernate.Automapping;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Conventions.Helpers;
using Gecko.Entities;
using NHibernate;
using NHibernate.Tool.hbm2ddl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Gecko.Util
{
    public class NHibernateHelper
    {
        private static ISessionFactory _sessionFactory;

        private static ISessionFactory SessionFactory
        {
            get
            {
                if (_sessionFactory == null)
                    InitializeSessionFactory();

                return _sessionFactory;
            }
        }


        private static void InitializeSessionFactory()
        {
            _sessionFactory = Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2008
                              .ConnectionString(conn => conn.FromConnectionStringWithKey("GeckoConn"))
                              .ShowSql()
                )
                .Mappings(m => m.AutoMappings.Add(AutoMap.AssemblyOf<UserInfo>().Where(t => t.Namespace == "Gecko.Entities")
                    .Conventions.Add(ConventionBuilder.Property.Always(instance =>
                    {
                        if (instance.Property.PropertyType == typeof(byte[]))
                        {
                            instance.Length(30000000);
                        }
                    }))))
                //.ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true))
                .BuildSessionFactory();
        }

        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }
    }
}